package com.csi.controller.history;

import com.alibaba.fastjson2.JSON;
import com.csi.domain.History;
import com.csi.pojo.PageBean;
import com.csi.pojo.Result;
import com.csi.service.HistoryService;
import com.csi.service.impl.HistoryServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/history/findAllPageByTypeController")
public class FindAllPageByTypeController extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");

        PrintWriter out = resp.getWriter();

        String currentPageNumberStr = req.getParameter("currentPageNumber");
        String operationType = req.getParameter("operationType");

        int currentPageNumber;

        // 参数校验：判断参数是否为空和是否为数字
        if (currentPageNumberStr == null || !currentPageNumberStr.matches("\\d+")) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("参数格式错误");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        } else {
            currentPageNumber = Integer.parseInt(currentPageNumberStr);
        }

        // 参数校验：判断 operationType 是否为空
        if (operationType == null || operationType.trim().isEmpty()) {
            Result result = new Result<>();
            result.setCode(400);
            result.setMsg("参数格式错误");
            out.print(JSON.toJSONString(result));
            out.flush();
            out.close();
            return;
        }

        HistoryService historyService = new HistoryServiceImpl();
        PageBean<History> pageBean = historyService.findAllPageByType(currentPageNumber,operationType);

        Result<PageBean<History>> result = new Result<>();
        result.setCode(200);
        result.setMsg("success");
        result.setDatas(pageBean);

        out.print(JSON.toJSONString(result));

        out.flush();
        out.close();
    }
}
